<template>
  <!-- 卡片容器 -->
  <div class="card-container">
    <el-card
      v-for="item in itemsWithQuestions"
      :key="item.id"
      class="question-card"
      @dblclick="handleCardDoubleClick"
    >
      <div class="card-header">
        <span class="card-title">{{ item.nam }}</span>
      </div>
      
      <el-tooltip
        :content="item.text"
        placement="top"
        :show-after="100"
      >
        <p class="card-content">{{ item.text }}</p>
      </el-tooltip>

<!-- 添加一个内容框 -->
<div class="content-box">
  <div class="box-title">最新提问</div>
  <template v-if="item.randomQuestions && item.randomQuestions.length">
    <p v-for="title in item.randomQuestions" 
       :key="title" 
       class="box-content">
      {{ title }}
    </p>
  </template>
  <p v-else class="box-content">暂无提问</p>
</div>
      
      <div class="card-footer">
        <!-- copylink 插槽始终显示 -->
        <slot
          name="copylink"
          :item="item"
        ></slot>
        <!-- 如果存在 edit 插槽则显示 -->
        <slot
          name="edit"
          v-if="$slots.edit"
          :item="item"
        ></slot>
      </div>
    </el-card>
  </div>
</template>

<script>
import { useRouter } from 'vue-router';
import { ref, watch } from 'vue';
import { get } from '@/net';
import { useStore } from 'vuex';

export default {
  name: 'Card',
  props: {
    items: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const store = useStore();
    const itemsWithQuestions = ref([]);

    // 从数组中随机选择n个元素
    const getRandomElements = (array, n) => {
      const shuffled = [...array].sort(() => 0.5 - Math.random());
      return shuffled.slice(0, n);
    };
     // 为单个item获取随机问题
     const fetchQuestionForItem = (item) => {
      return new Promise((resolve, reject) => {
        get(
          "/question_info/get_questions_from_box",
          { 
            bid: item.id, 
            pageNum: 1, 
            pageSize: 10
          },
          (message) => {
            if (message.data.questions && message.data.questions.length > 0) {
              const itemIndex = itemsWithQuestions.value.findIndex(i => i.id === item.id);
              if (itemIndex !== -1) {
                // 只保存title字段，并随机选择3个
                const allTitles = message.data.questions.map(q => q.title);
                const randomTitles = getRandomElements(allTitles, 5);

                itemsWithQuestions.value[itemIndex] = {
                  ...itemsWithQuestions.value[itemIndex],
                  randomQuestions: randomTitles
                };
              }
            }
            resolve();
          },
          (error) => {
            store.clearAccount();
            reject(error);
          }
        );
      });
    };

    // 为所有items获取随机问题
    const fetchQuestionsForAllItems = async () => {
      try {
        // 先更新本地数据
        itemsWithQuestions.value = [...props.items];   
        // 然后获取问题
        const promises = itemsWithQuestions.value.map(item => fetchQuestionForItem(item));
        await Promise.all(promises);
        console.log('获取所有问题后:', itemsWithQuestions.value);
      } catch (error) {
        console.error('Error fetching questions:', error);
      }
    };

    // 监听props.items的变化
    watch(
      () => props.items,
      (newItems) => {
        console.log('items changed:', newItems);
        if (newItems && newItems.length > 0) {
          fetchQuestionsForAllItems();
        }
      },
      { immediate: true } // 立即执行一次
    );

    const handleCardDoubleClick = (item) => {
      router.push({
        name: 'question',
        params: { id: item.id }
      });
    };

    return {
      handleCardDoubleClick,
      itemsWithQuestions,
    };
  }
};
</script>

<style scoped>
.card-container {
  height: 75%;
  display: grid;
  grid-template-columns: 1fr 1fr; /* 两列布局 */
  gap: 2%;
  overflow-y: auto; /* 超出高度时滚�? */
  padding: 2%;
  border: 1px solid #ddd;
  border-radius: 1%;
}
::v-deep .el-card__body {
  height: 90%;
  padding: auto;
}
.question-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  height: 400px;
  border: 1px solid #e0e0e0;
  border-radius: 0.4%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.question-card:hover {
  transform: scale(1.03);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.card-header {
  height: 10%;
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 1.2em;
  font-weight: bold;
}

.card-content {
  height: 12%;
  color: #666;
  margin-bottom: 12px;
  overflow: hidden;
}

.card-footer {
  height: 10%;
  display: flex;
  justify-content: space-between;
}
.content-box {
  height: 53%;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px 16px;
  background: linear-gradient(to right bottom, #f8fafc, #f1f5f9);
  margin-bottom: 12px;
  box-shadow: inset 0 1px 2px rgba(31, 35, 41, 0.05);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}
.content-box:hover {
  border-color: #c6e2ff;
  background: linear-gradient(to right bottom, #f8fafc, #ecf5ff);
  transition: all 0.3s ease;
}
.box-content {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.5;
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}
/* 标题样式 */
.box-title {
  font-size: 14px;
  color: #1f2937;
  font-weight: 600;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 添加一个小图标 */
.box-title:before {
  content: '';
  width: 4px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  display: inline-block;
}

</style>